﻿using System;
using System.Collections;
using System.Collections.Generic;
using CzfSDK;
using MySql.Data.MySqlClient;

namespace Server
{
	public static class ShopManager
	{
		const int RANDOM_SKILL = 1000001; // 随机一个技能

		// 获取商城商品列表
		public static List<Hashtable> GetAllShop(int userId)
		{
			return GetAll ();
		}

		// 购买商城道具
		public static string BuyShopItem(int userId, int shopId)
		{
			var item = Get (shopId);
			if (item == null)
				throw new CzfProtoException (Constants.ERR3, "没有这件商品");

			string cost = item.GetVal<int> ("pricetype") + "," + item.GetVal<int> ("price");
			string prize = item.GetVal<string> ("prize");

			// 计算奖励
			prize = FormatPrize (prize);

			// 扣钱
			BagManager.DelItem(cost, userId, "商城购买", shopId.ToString());

			// 发奖励
			BagManager.AddItem(prize, userId, "商城购买", shopId.ToString());

			return prize;
		}

		// 将奖励字段里面相同的道具合并,然后将随机道具随机出结果来
		static string FormatPrize(string prize)
		{
			string ret = "";
			HashSet<int> hasSkillId = new HashSet<int> ();

			foreach (var item in prize.Split('|')) {
				if (item.Trim () != "") {
					int id = Convert.ToInt32 (item.Trim ().Split (',') [0]);
					int count = Convert.ToInt32 (item.Trim ().Split (',') [1]);

					if (id == RANDOM_SKILL) {
						for (int i = 0; i < count; i++) {
							var skillId = GetRandomSkillId (RandomQuality ());
							int index = 0;
							while (hasSkillId.Contains (skillId)) {
								skillId = GetRandomSkillId (RandomQuality ());
								if (index++ > 100)
									break;
							}
							hasSkillId.Add (skillId);
							ret += skillId + ",1|";
						}
					} else {
						ret += id + "," + count + "|";
					}
				}
			}

			return ret.CzfTrimEnd ("|");
		}

		// 随机一个技能品质
		static int RandomQuality()
		{
			var rate4 = MConfig.GetGameConfig<int> ("rate4");
			var rate3 = MConfig.GetGameConfig<int> ("rate3");
			var rate2 = MConfig.GetGameConfig<int> ("rate2");

			var rand = CzfRandom.Range (1000);
			if (rand < rate4)
				return 4;
			else if (rand < rate4 + rate3)
				return 3;
			else if (rand < rate4 + rate3 + rate2)
				return 2;
			else
				return 1;
		}

		// 概率测试
		public static void TestRate()
		{
			int count4 = 0; // 橙色数量
			int count3 = 0; // 紫色数量
			int count2 = 0; // 蓝色数量
			int count1 = 0; // 绿色数量

			int _count4 = 0; // 橙色数量
			int _count3 = 0; // 紫色数量
			int _count2 = 0; // 蓝色数量
			int _count1 = 0; // 绿色数量

			int __count4 = 0; // 橙色数量
			int __count3 = 0; // 紫色数量
			int __count2 = 0; // 蓝色数量
			int __count1 = 0; // 绿色数量

			HashSet<int> has = new HashSet<int> (); // 已经抽到的技能

			Action<string> AddSkill = (string p) => {
				foreach (var item in p.Split('|')) {
					if (item.Trim () != "") {
						int id = Convert.ToInt32 (item.Trim ().Split (',') [0]);
						if (id.Between (BagManager.SKILL_ID_MIN, BagManager.SKILL_ID_MAX)) {
							bool repeat;

							if(!has.Contains (id)) {
								has.Add (id);
								repeat = false;
							} else {
								repeat = true;
							}


							var cfg = MConfig.GetSkillConfig(id);
							var quality = cfg.GetVal<int>("quality");
							if(quality == 4){
								count4++;
								_count4++;
								if(repeat)
									__count4++;
							}else if (quality == 3){
								count3++;
								_count3++;
								if(repeat)
									__count3++;
							}else if (quality == 2){
								count2++;
								_count2++;
								if(repeat)
									__count2++;
							}else {
								count1++;
								_count1++;
								if(repeat)
									__count1++;
							}


						}
					}
				}
			};

			// 放入初始技能
			AddSkill( MConfig.GetGameConfig<string>("initPrize"));

			int total = 0; // 总技能数量
			foreach (var skill in MConfig.GetSkillTemplate().Values) {
				if (skill.GetVal<int> ("shopQuality") > 0)
					total++;
			}

			CzfLog.Info ("抽奖概率测试, 初始技能 {0} 个,技能库 {1} 个 \n橙色概率:千分之{2}\n紫色概率:千分之{3}\n蓝色概率:千分之{4}".CzfFormat(
				has.Count,
				total,
				MConfig.GetGameConfig<int> ("rate4"),
				MConfig.GetGameConfig<int> ("rate3"),
				MConfig.GetGameConfig<int> ("rate2")
			));

			int count = 0; // 抽了多少次
			while(has.Count < total){
				var p = FormatPrize (RANDOM_SKILL + ",1");
				AddSkill (p);


				count++;

				if (count % 50 == 0) {
					CzfLog.Info ("抽 {0} 次, 技能数: {1}/{2} \n橙色 {3} 个, 重复 {7} 个\n紫色 {4} 个, 重复 {8} 个\n蓝色 {5} 个, 重复 {9} 个\n绿色 {6} 个, 重复 {10} 个".CzfFormat (
						count,
						has.Count,
						total,
						_count4,
						_count3,
						_count2,
						_count1,
						__count4,
						__count3,
						__count2,
						__count1
					));

					_count4 = 0;
					_count3 = 0;
					_count2 = 0;
					_count1 = 0;
					__count4 = 0;
					__count3 = 0;
					__count2 = 0;
					__count1 = 0;
				}
			}

			CzfLog.Info ("抽奖概率测试完成, 抽 {0} 次, 技能数: {1}/{2} \n橙色 {3} 个\n紫色 {4} 个\n蓝色 {5} 个\n绿色 {6} 个".CzfFormat (
				count,
				has.Count,
				total,
				count4,
				count3,
				count2,
				count1
			));
		}

		#region DB
		// 随机在数据库中选出一个指定品质的技能id
		public static int GetRandomSkillId(int quality)
		{
			var sql = "select id from skilltemp where quality = @quality order by shopQuality*rand() desc limit 1";
			return MysqlPool.current.ExecInt(sql,
				new MySqlParameter ("@quality", quality)
			);
		}

		public static List<Hashtable> GetAll()
		{
			var sql = "select * from shoptemplate";
			var dt = MysqlPool.current.ExecDataTable (sql);
			if (dt == null)
				return null;
			else
				return dt.ToList ();
		}

		public static Hashtable Get(int shopId)
		{
			var sql = "select * from shoptemplate where id = @id";
			var dr = MysqlPool.current.ExecDataRow (sql,
				new MySqlParameter ("@id", shopId)
			);
			if (dr == null)
				return null;
			else
				return dr.ToHashtable ();
		}
		#endregion
	}
}

